package com.imti.config;

import com.imti.api.Constants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

/**
 * @author API文档配置
 */
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(){
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //扫描指定包路径  参数为 包路径的字符串
                .apis(RequestHandlerSelectors.basePackage("com.imti.controller"))
                /// 任何请求都扫描
                .paths(PathSelectors.any())
                .build()
                //
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
        return docket;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(Constants.PROJECT_NAME)
                .description(Constants.PROJECT_DESCRIPTION)
                .contact(new Contact(Constants.PROJECT_CONTACT_NAME, Constants.PROJECT_SERVICE_URL, Constants.PROJECT_CONTACT_EMAIL))
                .version(Constants.PROJECT_VERSION)
                .build();
    }

    //设置鉴权策略
    private List<SecurityScheme> securitySchemes() {
        List<SecurityScheme> apiKeys = new ArrayList<>();
        apiKeys.add(new ApiKey("token", "hospital_token", "header"));
        return apiKeys;
    }

    // 配置默认的全局鉴权策略的开关，以及通过正则表达式进行匹配；默认 ^.*$ 匹配所有URL
    // *其中 securityReferences 为配置启用的鉴权策略
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("^(?!auth).*$")).build());
        return securityContexts;
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        //SecurityReference对象中的第一个参数需要和ApiKey中的name相同，实现计划和范围匹配
        securityReferences.add(new SecurityReference("token", authorizationScopes));
        return securityReferences;
    }
}
